package com.note.simpleadmin.module.shop.service;

import com.note.simpleadmin.dto.GoodsDto;
import com.note.simpleadmin.dto.GoodsSpecDto;
import com.note.simpleadmin.entity.TbColumn;
import com.note.simpleadmin.entity.TbGoods;
import com.note.simpleadmin.entity.TbGoodsSpec;
import com.note.simpleadmin.enu.AutomaticEnum;
import com.note.simpleadmin.enu.DeleteEnum;
import com.note.simpleadmin.enu.SaleEnum;
import com.note.simpleadmin.exception.DataNotExistException;
import com.note.simpleadmin.module.shop.dao.ColumnRepository;
import com.note.simpleadmin.module.shop.dao.GoodsRepository;
import com.note.simpleadmin.module.shop.dao.GoodsSpecRepository;
import com.note.simpleadmin.module.shop.vo.GoodsVo;
import com.note.simpleadmin.utils.DateUtil;
import com.note.simpleadmin.utils.IdGenerator;
import com.note.simpleadmin.vo.PageBean;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/***
 *@ClaseName:GoodsService
 *
 *@Decription:
 *
 *@Author: xubingbing
 *
 *@Date:2019/2/7 0007 23:35
 */
@Service
public class GoodsService {
    @Autowired
    private GoodsRepository goodsRepository;
    @Autowired
    private GoodsSpecRepository goodsSpecRepository;
    @Autowired
    private BrandService brandService;
    @Autowired
    private ClassifyService classifyService;
    @Autowired
    private ColumnService columnService;
    public void save(GoodsDto dto) {
        TbGoods goods=new TbGoods();
        goods.setId(IdGenerator.id());
        goods.setName(dto.getName());
        goods.setIntro(dto.getIntro());
        goods.setDetail(dto.getDetail());
        goods.setBrandId(dto.getBrandId());
        goods.setClassifyId(dto.getClassifyId());
        goods.setColumnId(dto.getColumnId());
        goods.setThumbnail(dto.getThumbnail());
        goods.setAutomatic(AutomaticEnum.NORMAL.getValue());
        goods.setPics(dto.getPics());
        goods.setSpecInfo(dto.getSpecInfo());
        goods.setSpecId(dto.getSpecId());
        goods.setSort(0);
        goods.setIsDelete(DeleteEnum.NORMAL.getValue());
        goods.setSale(SaleEnum.LOWER.getValue());
        goods.setCreateTime(DateUtil.getTimestamp());
        goodsRepository.save(goods);
        List<GoodsSpecDto> goodsSpecDtos= dto.getGoodsSpecDtos();
        for(GoodsSpecDto goodsSpecDto:goodsSpecDtos) {
            TbGoodsSpec goodsSpec=new TbGoodsSpec();
            goodsSpec.setId(IdGenerator.id());
            goodsSpec.setName(goodsSpecDto.getName());
            goodsSpec.setGoodsId(goods.getId());
            goodsSpec.setSalePrice(new BigDecimal(goodsSpecDto.getSalePrice()));
            goodsSpec.setMarketPrice(new BigDecimal(goodsSpecDto.getMarketPrice()));
            goodsSpec.setDiscount(0);
            goodsSpec.setHot(0);
            goodsSpec.setSaleNum(0);
            goodsSpec.setStock(0);
            goodsSpec.setStockWarning(0);
            goodsSpec.setSurplusNum(0);
            goodsSpec.setActive(goodsSpecDto.getActive());
            goodsSpec.setIsDelete(DeleteEnum.NORMAL.getValue());
            goodsSpecRepository.save(goodsSpec);
        }
    }
    //删除商品和商品下面规格
    public void delete(String id) throws DataNotExistException
    {
        TbGoods goods=goodsRepository.getOne(id);
        if(goods==null)
        {
            throw new DataNotExistException("数据不存在");
        }
        goods.setIsDelete(DeleteEnum.DELETE.getValue());
        goodsSpecRepository.delete(DeleteEnum.DELETE.getValue(),id);
        goodsRepository.save(goods);
    }
    public void shelf(String id,Integer status) throws DataNotExistException
    {
        TbGoods goods=goodsRepository.getOne(id);
        if(goods==null)
        {
            throw new DataNotExistException("数据不存在");
        }
        goods.setSale(status);
        goodsRepository.save(goods);
    }
    public void update(GoodsDto dto) throws DataNotExistException {

        TbGoods goods=goodsRepository.findByIdAndIsDelete(dto.getId(),DeleteEnum.NORMAL.getValue());
        if(goods==null) {
            throw new DataNotExistException("商品数据不存在");
        }
        goods.setName(dto.getName());
        goods.setIntro(dto.getIntro());
        goods.setDetail(dto.getDetail());
        goods.setBrandId(dto.getBrandId());
        goods.setClassifyId(dto.getClassifyId());
        goods.setColumnId(dto.getColumnId());
        goods.setThumbnail(dto.getThumbnail());
        goods.setAutomatic(AutomaticEnum.NORMAL.getValue());
        goods.setPics(dto.getPics());
        goods.setSpecInfo(dto.getSpecInfo());
        goods.setSpecId(dto.getSpecId());
        goodsRepository.save(goods);
        List<GoodsSpecDto> goodsSpecDtos= dto.getGoodsSpecDtos();
        //存在的goodsSpecId;
        List<String> goodsSpecIds=new ArrayList<String>();
        for(GoodsSpecDto goodsSpecDto:goodsSpecDtos) {
            if(StringUtils.isNotBlank(goodsSpecDto.getId())) {
                goodsSpecIds.add(goodsSpecDto.getId());
                TbGoodsSpec goodsSpec=goodsSpecRepository.getOne(goodsSpecDto.getId());
                if(goodsSpec==null) {
                    throw new DataNotExistException("商品规格id:"+goodsSpecDto.getId()+"不存在");
                }
                goodsSpec.setName(goodsSpecDto.getName());
                goodsSpec.setSalePrice(new BigDecimal(goodsSpecDto.getSalePrice()));
                goodsSpec.setMarketPrice(new BigDecimal(goodsSpecDto.getMarketPrice()));
                goodsSpec.setActive(goodsSpecDto.getActive());
                goodsSpecRepository.save(goodsSpec);
            }
            else{
                TbGoodsSpec goodsSpec=new TbGoodsSpec();
                String id=IdGenerator.id();
                goodsSpecIds.add(id);
                goodsSpec.setId(id);
                goodsSpec.setName(goodsSpecDto.getName());
                goodsSpec.setGoodsId(goods.getId());
                goodsSpec.setSalePrice(new BigDecimal(goodsSpecDto.getSalePrice()));
                goodsSpec.setMarketPrice(new BigDecimal(goodsSpecDto.getMarketPrice()));
                goodsSpec.setDiscount(0);
                goodsSpec.setHot(0);
                goodsSpec.setSaleNum(0);
                goodsSpec.setStock(0);
                goodsSpec.setStockWarning(0);
                goodsSpec.setSurplusNum(0);
                goodsSpec.setActive(goodsSpecDto.getActive());
                goodsSpec.setIsDelete(DeleteEnum.NORMAL.getValue());
                goodsSpecRepository.save(goodsSpec);
            }
        }
        goodsSpecRepository.deleteByGoodsIdAndIdNotIn(goods.getId(),goodsSpecIds);
    }
    public PageBean findByPage(String brandId,String classifyId,Integer sale,String name, Integer pageNumber,Integer limit)
    {
        if (pageNumber == null) {
            pageNumber = 0;
        }
        else
        {
            pageNumber=pageNumber-1;
        }
        if(limit==null)
        {
            limit=20;
        }
        Sort sort = new Sort(Sort.Direction.DESC, "sort");
        PageRequest pageRequest = new PageRequest(pageNumber, limit, sort);
        Specification<TbGoods> specification=new Specification<TbGoods>() {
            private static final long serialVersionUID = 1L;
            @Override
            public Predicate toPredicate(Root<TbGoods> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (StringUtils.isNotBlank(brandId)) {
                    predicates.add(criteriaBuilder.equal(root.get("brandId"), brandId));
                }
                if (StringUtils.isNotBlank(classifyId)) {
                    predicates.add(criteriaBuilder.equal(root.get("classifyId"), classifyId));
                }
                if (sale!=null) {
                    predicates.add(criteriaBuilder.equal(root.get("sale"), sale));
                }
                if (StringUtils.isNotBlank(name)) {
                    predicates.add(criteriaBuilder.equal(root.get("name"), name));
                }
                predicates.add(criteriaBuilder.equal(root.get("isDelete"),DeleteEnum.NORMAL.getValue()));
                return  criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        Page<TbGoods> page = goodsRepository.findAll(specification,pageRequest);
        List<TbGoods> goodsList=page.getContent();
        List<GoodsVo> goodsVos=new ArrayList<GoodsVo>();
        for(TbGoods goods:goodsList){
            GoodsVo goodsVo=new GoodsVo();
            goodsVo.setId(goods.getId());
            goodsVo.setName(goods.getName());
            goodsVo.setSale(goods.getSale());
            goodsVo.setAutomatic(goods.getAutomatic());
            goodsVo.setAutomaticTime(goods.getAutomaticTime());
            goodsVo.setBrandId(goods.getBrandId());
            goodsVo.setBrandName(brandService.getOne(goods.getBrandId()).getName());
            goodsVo.setClassifyId(goods.getClassifyId());
            goodsVo.setClassifyName(classifyService.getOne(goods.getClassifyId()).getName());
            if(StringUtils.isNotBlank(goods.getColumnId())) {
                goodsVo.setColumnId(goods.getColumnId());
                TbColumn columnm=columnService.getOne(goods.getColumnId());
                if(columnm!=null) {
                    goodsVo.setColunmName(columnm.getName());
                }
            }
            goodsVo.setSort(goods.getSort());
            goodsVo.setThumbnail(goods.getThumbnail());
            goodsVo.setCreateTime(goods.getCreateTime());
            goodsVo.setGoodsSpecList(goodsSpecRepository.findByGoodsId(goods.getId()));
            goodsVos.add(goodsVo);
        }PageBean<GoodsVo> pageBean=new PageBean(page.getTotalPages(),page.getTotalElements(),page.isFirst(),page.isEmpty(),page.getNumber(), goodsVos);
        return pageBean;
    }
    public GoodsVo getOne(String id) {
        TbGoods goods=goodsRepository.findByIdAndIsDelete(id,DeleteEnum.NORMAL.getValue());
        GoodsVo goodsVo=new GoodsVo();
        goodsVo.setId(goods.getId());
        goodsVo.setName(goods.getName());
        goodsVo.setSale(goods.getSale());
        goodsVo.setAutomatic(goods.getAutomatic());
        goodsVo.setAutomaticTime(goods.getAutomaticTime());
        goodsVo.setBrandId(goods.getBrandId());
        goodsVo.setBrandName(brandService.getOne(goods.getBrandId()).getName());
        goodsVo.setClassifyId(goods.getClassifyId());
        goodsVo.setClassifyName(classifyService.getOne(goods.getClassifyId()).getName());
        if(StringUtils.isNotBlank(goods.getColumnId())) {
            goodsVo.setColumnId(goods.getColumnId());
            goodsVo.setColunmName(columnService.getOne(goods.getColumnId()).getName());
        }
        goodsVo.setSpecId(goods.getSpecId());
        goodsVo.setSort(goods.getSort());
        goodsVo.setThumbnail(goods.getThumbnail());
        goodsVo.setPics(goods.getPics());
        goodsVo.setIntro(goods.getIntro());
        goodsVo.setDetail(goods.getDetail());
        goodsVo.setCreateTime(goods.getCreateTime());
        goodsVo.setGoodsSpecList(goodsSpecRepository.findByGoodsId(goods.getId()));
        goodsVo.setSpecInfo(goods.getSpecInfo());
        return goodsVo;
    }
}
